package cc.booku.owlbox.DataAcquisition;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.base.TBaseAdapter;
import com.timmy.tdialog.list.TListDialog;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.R;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class AcquisitionActivity extends AppCompatActivity {

    private RadioGroup rg_week_today;
    private RadioButton rb_week, rb_today;
    private Toolbar Toolbar;
    private TextView tv_url, tv_debug;
    private static final int WHAT_LOADING = 0;
    private TDialog tDialog;
    private WebView webView;
    //   private String wlzy_today="http://localhost:2021/api.php/timming/index.html?name=ok";
    private String wlzy_today = "http://103.45.145.67/DataAcquisition/api.php/timming/index.html?name=oktoday";
    private String wlzy_week = "http://103.45.145.67/DataAcquisition/api.php/timming/index.html?name=okweek";
    private String cjok = "http://103.45.145.67/AndroidApp/movietv/Statistics/acquisition.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_acquisition);
        //加载标题栏
        LoadToolbar();
        //状态栏颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));
        webView = (WebView) findViewById(R.id.webView);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        rg_week_today = (RadioGroup) findViewById(R.id.rg_week_today);

        rb_week = (RadioButton) findViewById(R.id.rb_week);
        rb_today = (RadioButton) findViewById(R.id.rb_today);
        tv_url = (TextView) findViewById(R.id.tv_url);
        tv_debug = (TextView) findViewById(R.id.tv_debug);
        //初始化


        rb_today.setChecked(true);
        tv_url.setText(wlzy_today);
        rg_week_today.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {

                    case R.id.rb_today:
                        tv_url.setText(wlzy_today);
                        break;

                    case R.id.rb_week:
                        tv_url.setText(wlzy_week);
                        break;
                }

            }
        });

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                initWebView();
                //Snackbar.make(view, tv_url.getText().toString().trim(), Snackbar.LENGTH_LONG)
                //  .setAction("Action", null).show();
//                new Thread()
//                {
//                    public void run() {
                //HttpResponse(tv_url.getText().toString().trim());
                //  loadingDialog();

//                    }
//                }.start();


            }
        });
    }

    public void loadingDialog() {
        tDialog = new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_loading)
                .setHeight(300)
                .setWidth(300)
                .setCancelableOutside(false)
                .create()
                .show();
        Thandler.sendEmptyMessageDelayed(WHAT_LOADING, 3 * 1000);

    }

    private void jsonResponse(String url) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {

                String res = response.body().string();
                JSONArray jsArr = JSONObject.parseArray(res);
                List<String> list = JSONObject.parseArray(jsArr.toJSONString(), String.class);
                bottomListDialog(list);

            }
        });

    }

    private void bottomListDialog(List<String> list) {
        new TListDialog.Builder(getSupportFragmentManager())
                .setScreenHeightAspect(AcquisitionActivity.this, 0.5f)
                .setScreenWidthAspect(AcquisitionActivity.this, 1.0f)
                .setGravity(Gravity.BOTTOM)
                .setAdapter(new TBaseAdapter<String>(R.layout.item_bottom_list_text, list) {

                    protected void onBind(BindViewHolder holder, int position, String s) {
                        //处理一下显示,和最后点击没有任何关系

                        JSONObject objsd = JSONObject.parseObject(s);
                        String vod_name = objsd.getString("vod_name");
                        holder.setText(R.id.tv, vod_name + "已加入库");
                    }
                })
                .setOnAdapterItemClickListener(new TBaseAdapter.OnAdapterItemClickListener<String>() {

                    public void onItemClick(BindViewHolder holder, int position, String s, TDialog tDialog) {
                        //Toast.makeText(NavDataActivity.this, "click:" + s, Toast.LENGTH_SHORT).show();

//                        //解析字符串
//                        JSONObject objsd = JSONObject.parseObject(s);
//                        String vod_class1 = objsd.getString("vod_class");
//                        String count1 = objsd.getString("count");
//
//                        Intent intent = new Intent();
//                        Bundle bundle = new Bundle();
//                        bundle.putString("vod_class1", vod_class1);
//                        bundle.putString("count1", count1);
//                        intent.putExtras(bundle);
//                        intent.setClass(NavDataActivity.this, LayPageActivity.class);
//                        startActivity(intent);

                        tDialog.dismiss();
                    }
                })

                .create()
                .show();
    }


    private Timer timer = new Timer();
    private TimerTask timerTask;

    private void HttpResponse(String url) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();
        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {


                timerTask = new TimerTask() {
                    @Override
                    public void run() {

                        String res = null;
                        try {
                            res = response.body().string();
                            if (!res.equals("")) {
                                Message msg = new Message();
                                msg.what = 12;
                                Bundle bundle = new Bundle();
                                bundle.putString("res", res);  //往Bundle中存放数据
                                msg.setData(bundle);//mes利用Bundle传递数据
                                Thandler.sendMessage(msg);

                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                };
                timer.schedule(timerTask, 100, 2000);
            }
        });

    }


    private Handler Thandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {


                case 12:
                    String str9 = msg.getData().getString("res");//接受msg传递过来的参数
                    tv_debug.setText(str9);
                    //jsonResponse(cjok);

                    //加个定时器，过一会儿重新赋值，拿到一部分数据重新赋值

//                        Timer timer = new Timer();
//                        TimerTask task = new TimerTask() {
//                            @Override
//                            public void run() {
//                                // 执行逻辑
//                                if (!isEmpty(str9) && str9.length()>=400) {
//                                    String Str = str9.substring(str9.length() - 400, str9.length());
//                                    tv_debug.setText(Str);
//                                }else {
//                                    tv_debug.setText(str9);
//                                }
//                                if(str9.indexOf("数据采集完成")!=-1){
//                                    // 关闭定时器
//                                    timer.cancel();
//                                }
//
//                            }
//                        };
//                    // 启动定时器，立即开始，1000毫秒触发一次
//                    timer.schedule(task,0,2000);
                    break;
                case WHAT_LOADING:
                    if (tDialog != null) {
                        tDialog.dismiss();
                    }
                    return;
            }
        }
    };

    //等待刷新函数
    private void WaitingRefresh() {
        Toast.makeText(AcquisitionActivity.this, "采集成功", Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 2000);
        // onCreate(null);//调用此方法刷新页面

    }

    private void LoadToolbar() {
        //新页面接收数据
        Toolbar = (Toolbar) findViewById(R.id.toolbar);
        Toolbar.setTitle("数据采集");
        setSupportActionBar(Toolbar);//利用Toolbar代替ActionBar
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                finish();
            }
        });

    }


    //******************************************************************************************

    private void initWebView() {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //系统默认会打开系统浏览器去打开网页，为了要显示在自己的webview中必须设置这个属性
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
            //加载开始时调用

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (null == view) {
                    view.loadUrl(tv_url.getText().toString().trim());
                }
                super.onPageStarted(view, url, favicon);

            }
            // 加载结束时调用

            @Override
            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);

            }

            private boolean isSuccess = false;
            private boolean isError = false;

            //加载错误的时候会回调，在其中可做错误处理，比如再请求加载一次，或者提示404的错误页面
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                if (!isError) {
                    isSuccess = true;
                    webView.loadUrl(tv_url.getText().toString().trim());
                    //回调成功后的相关操作
                }
                isError = false;
                // webView.loadUrl("file:////android_asset/app_updatainfo.html");
            }

            //当接收到https错误时，会回调此函数，在其中可以做错误处理
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //webView.loadUrl("file:////android_asset/app_updatainfo.html");
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                url = url.toLowerCase();
                if (!url.contains(url)) {
                    if (!ADFilterTool.hasAd(AcquisitionActivity.this, url)) {
                        return super.shouldInterceptRequest(view, url);
                    } else {
                        return new WebResourceResponse(null, null, null);
                    }
                } else {
                    return super.shouldInterceptRequest(view, url);
                }
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            //加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.e("WebView>>>>>>>", newProgress + "");
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onRequestFocus(WebView view) {
                super.onRequestFocus(view);
            }

            @Override
            public void onCloseWindow(WebView window) {
                super.onCloseWindow(window);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

        });

        webView.loadUrl(tv_url.getText().toString().trim());
        // 得到setting
        WebSettings webSettings = webView.getSettings();
        //设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        //支持的语言类型
        webSettings.setDefaultTextEncodingName("UTF-8");
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);

        webSettings.setDomStorageEnabled(true);


//关键代码
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        //这里处理返回键事件
                        if (webView.canGoBack()) {
                            webView.goBack();
                            //Toast.makeText(getActivity(), "ok", Toast.LENGTH_SHORT).show();
                            return true;
                        }
                    }
                }
                return false;
            }
        });
    }
}


class ADFilterTool {
    public static boolean hasAd(Context context, String url) {
        Resources res = context.getResources();
        String[] adUrls = res.getStringArray(R.array.adBlockUrl);
        for (String adUrl : adUrls) {
            if (url.contains(adUrl)) {
                return true;
            }
        }
        return false;
    }
}



